﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Universum.Model.Domain.Blogs;
using Universum.Infrastructure.Persistence;
using System.Security.Principal;
using Universum.Infrastructure.Persistence.Queries;
using Universum.Infrastructure.Persistence.Queries.Blog;
using Universum.Model.Services.Indexing;
using System.Text;

namespace Universum.Model.Services.Blog
{
	public class BlogArticleServiceImpl
		:IBlogArticleService
	{
		IRepository _Repository;
		IPrincipal _Principal;
		IBlogService _BlogService;
		IBlogArticleIndexingService _BlogArticleIndexingService;
		IFriendlyUrlService _FriendlyUrlService;
		public BlogArticleServiceImpl(IRepository repository,
			IPrincipal principal,
			IBlogService blogService,
			IBlogArticleIndexingService blogArticleIndexingService,
			IFriendlyUrlService friendlyUrlService
			)
		{
			this._Repository = repository;
			this._Principal = principal;
			this._BlogService = blogService;
			this._BlogArticleIndexingService = blogArticleIndexingService;
			this._FriendlyUrlService = friendlyUrlService;
		}
		#region IBlogArticleService Members

		public Universum.Model.Domain.Blogs.BlogArticle Create()
		{
			return new BlogArticle
			{
				ID = Guid.NewGuid(),
				BlogId = _BlogService.GetBlogByOwner(_Principal.Identity.Name).ID,
				Username = _Principal.Identity.Name,
				Created = DateTime.Now
			};
		}

		public BlogArticle GetArticleById(Guid id)
		{
			return _Repository.Load<BlogArticle>(id);
		}

		public void RemoveArticleById(Guid id)
		{
			var blogArticle = GetArticleById(id);
			_Repository.Remove<BlogArticle>(blogArticle);
			_BlogArticleIndexingService.Remove(blogArticle);
		}

		public void SaveOrUpdate(BlogArticle article)
		{
			var sb = new StringBuilder(article.ID.ToInt().ToString())
			.Append("-").Append(article.Title);
			article.Slug = sb.ToString().AsSlug();
			_Repository.SaveOrUpdate(article);
			_BlogArticleIndexingService.Update(article);
		}

	
		public BlogArticle GetArticleBySlug(string id)
		{
			var article = (BlogArticle) _Repository.Query(new BlogArticleBySlug(id)).FirstOrDefault();
			return article;
		}

	
		public void SaveComment(BlogCommentArticle comment)
		{

			_Repository.SaveOrUpdate(comment);
		}

		
		public IList<BlogCommentArticle> GetCommentsByArticleId(Guid guid)
		{
			var result =  _Repository.Query(new Universum.Infrastructure.Persistence.Queries.Blog.BlogArticleCommentByBlogArticleId(guid)).OrderBy(item=>item.Publish).ToList();
			return result;
		}

		#endregion
	}
}
